﻿using AnlianCommon.Common.Domains.SheepFarmHouse;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.SheepFarmes
{
    public class SheepFarmsUpdateHandler : IRequestHandler<SheepFarmsUpdateCommand, Result>
    {
        private readonly IBaseRepository<SheepFarm> _sheepFarmRepository;
        private readonly IMapper _mapper;

        public SheepFarmsUpdateHandler(IBaseRepository<SheepFarm> sheepFarmRepository, IMapper mapper)
        {
            _sheepFarmRepository = sheepFarmRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SheepFarmsUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Updated };
            try
            {
                var sheepFarm = await(await _sheepFarmRepository.GetAll()).Where(c => c.FarmId == request.FarmId).FirstOrDefaultAsync();
                if (sheepFarm != null)
                {
                    sheepFarm.UpdatedOwnerId = "张三";
                    sheepFarm.UpdatedTime = DateTime.Now;
                    var res = await _sheepFarmRepository.Update(sheepFarm);
                    if (res > 0)
                    {
                        result.Code= (int)CommonErrorCode.Success;
                        result.Msg = "修改成功";
                    }
                    else
                    {
                        result.Code = (int)CommonErrorCode.Updated;
                        result.Msg = "修改失败";
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}